package com.example.demo.test.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

public class WorkerServerTest3 {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("thread-boss");
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss=Selector.open();
        ssc.register(boss,SelectionKey.OP_ACCEPT,null);
        ssc.bind(new InetSocketAddress(8082));
        Worker[] workers=new Worker[2];
        for (int i=0;i< workers.length;i++){
            workers[i]=new Worker("worker-"+i);
        }
        AtomicInteger index=new AtomicInteger();
        while (true){
            boss.select();
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if(key.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    System.out.println("和客户端建立连接"+sc);
                    System.out.println("before register..");
                    workers[index.getAndIncrement()% workers.length].register(sc);
                    System.out.println("after register..");
                }
            }
        }
    }
    static class Worker implements Runnable{
        private String name;
        private Thread thread;
        private Selector selector;
        private volatile boolean start=false;

        public Worker(String name){
            this.name=name;
        }

        /**
         * 初始化线程和selector
         *
         *
         */
        public void register(SocketChannel sc) throws IOException {
            if(!start){
                System.out.println("线程【"+name+"】开始初始化");
                selector =Selector.open();
                thread=new Thread(this,name);
                thread.start();
                start=true;
            }
            selector.wakeup();
            sc.register(selector,SelectionKey.OP_READ,null);
        }
        @Override
        public void run() {
            while (true){
                try {
//                    System.out.println("监听事件");
                    selector.select();
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if(key.isReadable()){
                            System.out.println("读取客户端数据");
                            ByteBuffer byteBuffer=ByteBuffer.allocate(10);
                            SocketChannel channel = (SocketChannel) key.channel();
                            channel.read(byteBuffer);
                            byteBuffer.flip();
                            System.out.println("客户端数据为："+byteBuffer.toString());
                            if(!byteBuffer.hasRemaining()){
                                byteBuffer.clear();
                                key.interestOps(key.interestOps()-SelectionKey.OP_READ);
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
